package com.yql.framework.web.exception;

import com.yql.commonextend.exception.BusinessException;
import com.yql.commonextend.exception.CryptoException;
import com.yql.commonextend.response.CommonResponse;
import com.yql.commonextend.response.ResponseConstant;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器（业务模块使用，重写此类覆盖yql-framewokr中已存在的GlobalExceptionHandler）
 * @// FIXME: 2021/6/28
 * @author chenjun
 */
@RestControllerAdvice
public class GlobalExceptionHandler
{
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 请求方式不支持
     */
    @ExceptionHandler({ HttpRequestMethodNotSupportedException.class })
    public CommonResponse<T> handleException(HttpRequestMethodNotSupportedException e)
    {
        log.error("不支持' " + e.getMethod() + "'请求"+e.getMessage(), e);
        CommonResponse<T> cr = new CommonResponse<>();
        cr.setCode(ResponseConstant.RESP_RUNTIME_ERROR_CODE);
        cr.setMsg(ResponseConstant.RESP_RUNTIME_ERROR_MESG);
        return cr;
    }

    /**
     * 加解密异常，可能是非法操作
     */
    @ExceptionHandler({ CryptoException.class })
    public CommonResponse<T> handleException(CryptoException e)
    {
        log.error("加解密异常:", e);
        CommonResponse<T> cr = new CommonResponse<>();
        cr.setCode(ResponseConstant.RESP_ERROR_CODE);
        cr.setMsg(ResponseConstant.RESP_ERROR_MESG);
        return cr;
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public CommonResponse notFount(RuntimeException e)
    {
        log.error("运行时异常:", e);
        CommonResponse<T> cr = new CommonResponse<>();
        cr.setCode(ResponseConstant.RESP_RUNTIME_ERROR_CODE);
        cr.setMsg(ResponseConstant.RESP_RUNTIME_ERROR_MESG);
        return cr;
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public CommonResponse handleException(Exception e)
    {
        log.error("系统异常："+e.getMessage(), e);
        CommonResponse<T> cr = new CommonResponse<>();
        cr.setCode(ResponseConstant.RESP_RUNTIME_ERROR_CODE);
        cr.setMsg(ResponseConstant.RESP_RUNTIME_ERROR_MESG);
        return cr;
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public CommonResponse businessException(Exception e)
    {
        String[] msg = e.getMessage().split("&&");
        if(msg.length != 2){//code和msg两个字段
            log.error("GlobalExceptionHandler业务异常返回有误！",e);
        }
        log.info("业务提示："+e.getMessage());//不属于异常，不打印堆栈信息
        CommonResponse<T> cr = new CommonResponse<>();
        cr.setCode(Integer.valueOf(msg[0]));
        cr.setMsg(msg[1]);
        return cr;
    }

}
